package com.charge.web;

import com.charge.domain.Account;
import com.charge.domain.User;
import com.charge.domain.UserIncomeType;
import com.charge.domain.UserSpendingType;
import com.charge.dto.ChargeAddDTO;
import com.charge.dto.ChargeImportDTO;
import com.charge.dto.ChargeRecordDTO;
import com.charge.service.AccountService;
import com.charge.service.ChargeRecordService;
import com.charge.service.IncomeService;
import com.charge.service.SpendingService;
import com.charge.util.*;
import com.charge.vo.ChargeRecordVO;
import com.charge.vo.ProjectVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Description :
 * Author : 91658
 * Date : 2018/6/8 11:14
 **/
@Controller
@RequestMapping("/charge")
public class ChargeController {

    @Autowired
    private ChargeRecordService chargeRecordService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private IncomeService incomeService;

    @Autowired
    private SpendingService spendingService;

    @RequestMapping(value = "/charge_manage")
    public String chargeManage(HttpServletRequest request, HttpSession session) {
        User user = (User) session.getAttribute("user");
        ChargeRecordDTO chargeRecordDTO = new ChargeRecordDTO();
        chargeRecordDTO.setUserId(user.getId());
        Account account = new Account();
        account.setUserId(user.getId());
        List<Account> accountList = accountService.selectAccountList(account);
        request.setAttribute("accountList", accountList);

        UserIncomeType userIncomeType = new UserIncomeType();
        userIncomeType.setUserId(user.getId());
        List<UserIncomeType> userIncomeTypeList = incomeService.selectIncomeList(userIncomeType);
        request.setAttribute("incomeList", userIncomeTypeList);

        UserSpendingType userSpendingType = new UserSpendingType();
        userSpendingType.setUserId(user.getId());
        List<UserSpendingType> userSpendingTypeList = spendingService.selectSpendingList(userSpendingType);
        request.setAttribute("spendingList", userSpendingTypeList);

        Integer count = chargeRecordService.selectChargeRecordCount(chargeRecordDTO);
        Page page = new Page(1, 10, count);
        chargeRecordDTO.setBeginRow(page.getBeginRow());
        chargeRecordDTO.setEndRow(page.getEndRow());
        List<ChargeRecordVO> chargeRecordVOList = chargeRecordService.selectChargeRecordList(chargeRecordDTO);
        request.setAttribute("result", chargeRecordVOList);
        return "/charge/charge_manage";
    }

    @RequestMapping("/charge_record")
    @ResponseBody
    public LayResponse<List<ChargeRecordVO>> chargeRecord(ChargeRecordDTO chargeRecordDTO, HttpSession session) {
        User user =(User) session.getAttribute("user");
        chargeRecordDTO.setUserId(user.getId());
        Integer count = chargeRecordService.selectChargeRecordCount(chargeRecordDTO);
        Page page = new Page(chargeRecordDTO.getPageNo(), chargeRecordDTO.getPageSize(), count);
        chargeRecordDTO.setBeginRow(page.getBeginRow());
        chargeRecordDTO.setEndRow(page.getEndRow());
        List<ChargeRecordVO> chargeRecordVOList = chargeRecordService.selectChargeRecordList(chargeRecordDTO);
        return LayResponse.createBySuccess(Const.SUCCESS, page.getTotal(), chargeRecordVOList);
    }

    @RequestMapping("/upload")
    @ResponseBody
    public WebResponse<String> upload(HttpServletRequest request, HttpSession session) {
        try {
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (commonsMultipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = commonsMultipartResolver.resolveMultipart(request);
                Iterator<String> fileNames = multiRequest.getFileNames();
                while (fileNames.hasNext()) {
                    // 取得上传文件
                    MultipartFile file = multiRequest.getFile(fileNames.next());
                    if (file != null) {
                        // 取得当前上传文件的文件名称
                        String myFileName = file.getOriginalFilename();
                        // 如果名称不为“”,说明该文件存在，否则说明该文件不存在
                        if (myFileName.trim() != "") {
                            ImportExcel ei =  new ImportExcel(file, 0, 0);
                            List<ChargeImportDTO> importList = ei.getDataList(ChargeImportDTO.class);
                            if (CollectionUtils.isNotEmpty(importList)) {
                                User user = (User) session.getAttribute("user");
                                chargeRecordService.importChargeRecord(importList, user.getId());
                                return WebResponse.createBySuccess(Const.SUCCESS, "");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return WebResponse.createByError(Const.ERROR, "");
        }
        return WebResponse.createByFail(Const.FAIL, "");
    }

    @RequestMapping("/add_charge_frame")
    public String addChargeFrame(HttpServletRequest request, HttpSession session) {
        User user = (User) session.getAttribute("user");

        Account account = new Account();
        account.setUserId(user.getId());
        List<Account> accountList = accountService.selectAccountList(account);
        request.setAttribute("accountList", accountList);
        return "/charge/add_charge_frame";
    }

    @RequestMapping(value = "/add_charge", produces = "application/json;charset=utf-8")
    @ResponseBody
    public WebResponse<String> addCharge(@RequestBody List<ChargeAddDTO> chargeAddDTOList, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (CollectionUtils.isNotEmpty(chargeAddDTOList)) {
            chargeRecordService.addChargeRecord(chargeAddDTOList, user.getId());
            return WebResponse.createByFail(Const.SUCCESS, "");
        }
        return WebResponse.createBySuccess(Const.FAIL, "");
    }

    @RequestMapping("/project_list")
    @ResponseBody
    public WebResponse<List<ProjectVO>> projectList(Integer paymentsType, HttpSession session) {
        if (paymentsType == null) {
            return WebResponse.createByFail(Const.FAIL, null);
        }
        User user = (User) session.getAttribute("user");
        List<ProjectVO> projectVOList = new ArrayList<>();
        if (paymentsType == 2) {
            UserIncomeType userIncomeType = new UserIncomeType();
            userIncomeType.setUserId(user.getId());
            List<UserIncomeType> userIncomeTypeList = incomeService.selectIncomeList(userIncomeType);
            if (CollectionUtils.isNotEmpty(userIncomeTypeList)) {
                for (UserIncomeType incomeType : userIncomeTypeList) {
                    ProjectVO projectVO = new ProjectVO();
                    projectVO.setProjectId(incomeType.getId());
                    projectVO.setProjectName(incomeType.getIncomeName());
                    projectVOList.add(projectVO);
                }
            }
        } else if (paymentsType == 1) {
            UserSpendingType userSpendingType = new UserSpendingType();
            userSpendingType.setUserId(user.getId());
            List<UserSpendingType> userSpendingTypeList = spendingService.selectSpendingList(userSpendingType);
            if (CollectionUtils.isNotEmpty(userSpendingTypeList)) {
                for (UserSpendingType spendingType : userSpendingTypeList) {
                    ProjectVO projectVO = new ProjectVO();
                    projectVO.setProjectId(spendingType.getId());
                    projectVO.setProjectName(spendingType.getSpendingName());
                    projectVOList.add(projectVO);
                }
            }
        }
        return WebResponse.createBySuccess(Const.SUCCESS, projectVOList);
    }

}
